﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SocketApp
{
    internal class SocketServer
    {
        static Socket tcpServer;
        public static void Init()
        {
            tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建socket对象
            tcpServer.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 18200));//服务端通信的地址和端口
            tcpServer.Listen(100);//最大连接数

            Console.WriteLine("服务器已启动，等待连接.......");

            while (true)//循环监听是否有数据上报
            {
                Socket clientSocket = tcpServer.Accept();
                var epoint = (clientSocket.RemoteEndPoint as IPEndPoint);
                Console.WriteLine(epoint.Address + ":" + epoint.Port + "已连接");
                Task.Run(() => ServerRead(clientSocket));
            }
        }
        private static void ServerRead(Socket clientSocket)
        {
            string recvStr = "";
            byte[] recvBytes = new byte[1024];
            int bytes;
            do
            {
                bytes = clientSocket.Receive(recvBytes, recvBytes.Length, 0); //从客户端接受消息
                recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
            } while (bytes == 1024);
            Console.WriteLine("{0} 收到：{1}", clientSocket.RemoteEndPoint.ToString(), recvStr);
        }
    }
}
